package com.c.securityservice;

import com.c.entity.Permission;
import com.c.entity.Role;
import com.c.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * @author wangxiangli
 * @create 2022-12-23-22:05
 */
@Service
public class MyUserDetailsService implements UserDetailsService {

    @Autowired
    private UserService userService;


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
//        QueryWrapper<com.c.entity.User> wrapper=new QueryWrapper<>();
//        wrapper.eq("username",username);
//        com.c.entity.User user = userMapper.selectOne(wrapper);
        com.c.entity.User user = userService.findByUsername(username);
        if(user==null){
            return null;
        }
        //List<GrantedAuthority> authslist= AuthorityUtils.commaSeparatedStringToAuthorityList("admin");
       // return new User(user.getUsername(),user.getPassword(),authslist);
        List<GrantedAuthority> list=new ArrayList<>();

        Set<Role> roles=user.getRoles();
        if(roles!=null){
            for(Role role:roles){
                list.add(new SimpleGrantedAuthority(role.getKeyword()));
                Set<Permission> permissions=role.getPermissions();
                if(permissions!=null){
                    for(Permission permission:permissions){
                        list.add(new SimpleGrantedAuthority(permission.getKeyword()));

                    }
                }
            }
        }
        return new User(username, user.getPassword(),user.getState().equals("1"),true,true,true, list);
    }
}
